#include "GameEngine.h"
#include "GameState.h"

void GameEngine::Init()
{
    Window.create(sf::VideoMode(SCREENWIDTH, SCREENHEIGHT, 32), "Test");
    //initialize the game clock
    gameClock.restart();
    //Window.setFramerateLimit(FRAMERATE);
}

void GameEngine::Cleanup()
{
	// cleanup the all states
	while ( !states.empty() ) {
		states.back()->Cleanup();
		states.pop_back();
	}

	// Shut down the program
}

//used to initialize a new state
void GameEngine::ChangeState(GameState* state)
{
	// cleanup the current state
	if ( !states.empty() ) {
		states.back()->Cleanup();
		states.pop_back();
	}

	// store and init the new state
	states.push_back(state);
	states.back()->Init(Window);
}

// pause the existing state and starts a new one
void GameEngine::PushState(GameState* state)
{
	// pause current state
	if ( !states.empty() ) {
		states.back()->Pause();
	}

	// store and init the new state
	states.push_back(state);
	states.back()->Init(Window);
}

//stops the current state and resumes the new one
void GameEngine::PopState()
{
	// cleanup the current state
	if ( !states.empty() ) {
		states.back()->Cleanup();
		states.pop_back();
	}

	// resume previous state
	if ( !states.empty() ) {
		states.back()->Resume();
	}
}

void GameEngine::Events()
{
	// let the state handle events
	states.back()->Events(this, Window);
}

void GameEngine::Update()
{

	// let the state update the game if enough time has passed
	// 25 cycles / second  .001 second/ms 25 *.001 cycles /ms
	if(gameClock.getElapsedTime().asMilliseconds() >= (1/(GAMESPEED * .001))){
        states.back()->Update(this, Window);
        gameClock.restart();
	}

}

void GameEngine::Render()
{
	// let the state draw the screen
	states.back()->Render(this, Window);
}
